import 'package:demo/tools/tools_storage.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:demo/event/event_setting.dart';
import 'package:demo/views/base/base_controller.dart';
import 'package:demo/tools/tools_enum.dart';
import 'package:demo/tools/tools_sqlite.dart';

class FriendDetailsController extends BaseController {
  TextEditingController remarkController = TextEditingController();
  TextEditingController nicknameController = TextEditingController();
  // 当前对象
  LocalUser localUser = ToolsStorage().local();
  // 好友ID
  late String userId;

  // 获取本地详情
  Future<void> getById() async {
    // 执行
    ChatFriend? friend = await ToolsSqlite().friend.getById(userId);
    if (friend != null) {
      // 赋值
      refreshData = friend;
      // 默认值
      remarkController.text = friend.remark;
      nicknameController.text = friend.nickname;
    }
    update();
  }

  // 提交
  setRemark() async {
    String remark = remarkController.text.trim();
    // 更新
    refreshData.remark = remark;
    update();
    // 通知
    EventSetting().handle(
      SettingModel(
        SettingType.friend,
        primary: userId,
        label: 'remark',
        value: remark,
      ),
    );
    // 提醒
    EasyLoading.showToast('操作成功');
    // 返回
    Get.back();
  }

  @override
  void onInit() {
    super.onInit();
    refreshData = ChatFriend.init();
    userId = Get.arguments;
    getById();
    // 监听好友
    subscription = EventSetting().event.stream.listen((model) async {
      if (SettingType.friend == model.setting) {
        getById();
      }
    });
  }

  @override
  void onClose() {
    remarkController.dispose();
    nicknameController.dispose();
    super.onClose();
  }
}
